<template>
  <div class="admin-dashboard-container">
    <h2 class="page-title">数据预览</h2>

    <!-- 用户统计和管理员信息卡片 -->
    <el-row :gutter="20">
      <!-- 用户统计卡片 -->
      <el-col :span="12">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>用户统计</span>
              <el-button class="button" link type="primary" @click="goToUserInfo">查看用户列表</el-button>
            </div>
          </template>
          <div class="card-content">
            <el-descriptions 
              :column="1" 
              border 
              size="small"
              :cell-style="{ padding: '8px' }"
              :label-style="{ 
                width: '120px',
                color: '#606266',
                fontWeight: '500'
              }"
            >
              <el-descriptions-item label="注册用户总数">
                <span class="info-text">{{ userStats.totalUsers }} 人</span>
              </el-descriptions-item>
              <el-descriptions-item label="今日新增用户">
                <span class="info-text">{{ userStats.newUsersToday }} 人</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>

      <!-- 管理员信息卡片 -->
      <el-col :span="12">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>管理员信息</span>
              <el-button class="button" link type="primary" @click="goToAdminInfo">查看详情</el-button>
            </div>
          </template>
          <div class="card-content">
            <el-descriptions 
              :column="2" 
              border 
              size="small"
              :cell-style="{ padding: '8px' }"
              :label-style="{ 
                width: '80px',
                color: '#606266',
                fontWeight: '500'
              }"
            >
              <el-descriptions-item label="用户名">
                <span class="info-text">{{ adminInfo.username }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="真实姓名">
                <span class="info-text">{{ adminInfo.realName }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="角色">
                <el-tag size="small" type="success">{{ adminInfo.role }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                <span class="info-text">{{ adminInfo.email }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="电话">
                <span class="info-text">{{ adminInfo.phone }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="最后登录">
                <span class="info-text">{{ adminInfo.lastLoginTime }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新操作日志和题目统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;" class="aligned-cards-row">
       <!-- 最新操作日志卡片 -->
      <el-col :span="12">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>最新操作日志</span>
               <el-button class="button" link type="primary" @click="goToLogs">查看全部日志</el-button>
            </div>
          </template>
          <div class="card-content">
            <ul class="log-list">
              <li v-for="(log, index) in latestLogs" :key="index">
                {{ log.date }} - {{ log.user }}：{{ log.action }}
              </li>
            </ul>
             <el-empty v-if="latestLogs.length === 0" description="暂无日志" :image-size="50"></el-empty>
          </div>
        </el-card>
      </el-col>
       <!-- 题目统计卡片 (使用图表) -->
      <el-col :span="12">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>题目统计</span>
              <el-button class="button" link type="primary" @click="goToQuestionManagement">查看题目列表</el-button>
            </div>
          </template>
          <div class="card-content chart-container">
             <Pie v-if="questionChartData.labels.length > 0 && questionChartData.datasets[0].data.length > 0" :data="questionChartData" :options="questionChartOptions" />
             <el-empty v-else description="暂无题目统计数据" :image-size="50"></el-empty>
          </div>
        </el-card>
      </el-col>
     </el-row>

    <!-- 反馈概览卡片 (移至下方，横向占满) -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
         <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>反馈概览</span>
              <el-button class="button" link type="primary" @click="goToFeedbackResponses">查看我的回复</el-button>
            </div>
          </template>
          <div class="card-content">
            <el-descriptions :column="3" border>
              <el-descriptions-item label="待处理反馈">{{ feedbackStats.pendingCount }} 条</el-descriptions-item>
              <el-descriptions-item label="用户体验反馈总数">{{ feedbackStats.experienceCount }} 条</el-descriptions-item>
              <el-descriptions-item label="答题疑惑反馈总数">{{ feedbackStats.questionCount }} 条</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
// 引入图表组件和 ChartJS 注册器
import { Pie } from 'vue-chartjs';
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js';
import { useUserStore } from '../../store/UserStore'

// 注册 ChartJS 组件
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale);

export default {
  name: 'AdminIndex',
  components: {
    Pie,
  },

  data() {
    return {
      feedbackStats: {
        pendingCount: 0,
        experienceCount: 0,
        questionCount: 0
      },
      userStats: {
        totalUsers: 0,
        newUsersToday: 0,
        activeUsers: 0
      },
      questionStats: {
        totalQuestions: 0,
        easyCount: 0,
        mediumCount: 0,
        hardCount: 0
      },
      latestLogs: [],
      adminInfo: {
        username: '加载中...',
        role: '加载中...',
        realName: '加载中...',
        email: '加载中...',
        phone: '加载中...',
        lastLoginTime: '加载中...'
      },
      // 题目统计图表数据和配置
      questionChartData: {
        labels: [],
        datasets: [
          {
            backgroundColor: ['#41B883', '#E46651', '#00D8FF', '#DD1B16'],
            data: []
          }
        ]
      },
      questionChartOptions: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
           legend: {
            position: 'right',
           }
        }
      }
    };
  },

  methods: {
    // 获取反馈统计数据
    async fetchFeedbackStats() {
      try {
        const response = await this.$http.get('http://localhost:8080/feedback-vo/list')
        const feedbackList = response.data

        let pendingCount = 0
        let experienceCount = 0
        let questionCount = 0

        feedbackList.forEach(item => {
          if (item.status === 0) {
            pendingCount++
          }
          if (item.feedbackType === 1) {
            experienceCount++
          } else if (item.feedbackType === 2) {
            questionCount++
          }
        })

        this.feedbackStats = {
          pendingCount,
          experienceCount,
          questionCount
        }
      } catch (error) {
        console.error('获取反馈统计失败:', error)
        ElMessage.error('获取反馈统计失败')
        this.feedbackStats = {
          pendingCount: 0,
          experienceCount: 0,
          questionCount: 0
        }
      }
    },

    // 获取用户统计数据
    async fetchUserStats() {
      try {
        console.log('开始获取用户统计数据...')
        const response = await this.$http.get('http://localhost:8080/user/user_findall')
        const response2 = await this.$http.get('http://localhost:8080/user/newuserstoday')
        
        console.log('所有用户数据:', response.data)
        console.log('今日新增用户数据:', response2.data)
        
        this.userStats = {
          totalUsers: response.data.length || 0,
          newUsersToday: response2.data.length || 0,
          activeUsers: 0
        }
        
        console.log('处理后的用户统计数据:', this.userStats)
      } catch (error) {
        console.error('获取用户统计失败:', error)
        ElMessage.error('获取用户统计失败')
      }
    },

    // 获取题目统计数据
    async fetchQuestionStats() {
      try {
        const response = await this.$http.get('http://localhost:8080/question/all')
        const questions = response.data.filter(q => q.status === 1)
        
        // 统计各难度题目数量
        const difficultyStats = {
          easy: questions.filter(q => q.difficulty === 1).length,
          medium: questions.filter(q => q.difficulty === 2).length,
          hard: questions.filter(q => q.difficulty === 3).length
        }
        
        // 更新图表数据
        this.questionChartData = {
          labels: ['简单', '中等', '较难'],
          datasets: [{
            data: [difficultyStats.easy, difficultyStats.medium, difficultyStats.hard],
            backgroundColor: ['#67C23A', '#E6A23C', '#F56C6C']
          }]
        }
      } catch (error) {
        console.error('获取题目统计失败:', error)
        ElMessage.error('获取题目统计失败')
      }
    },

    // 获取最新操作日志
    async fetchLatestLogs() {
      try {
        const response = await this.$http.get('http://localhost:8080/adminLogs/all')
        if (!response.data || !Array.isArray(response.data)) {
          throw new Error('日志数据格式错误')
        }
        
        // 获取所有日志并按时间倒序排序，取前5条
        this.latestLogs = response.data
          .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
          .slice(0, 5)
          .map(log => ({
            date: this.formatDate(log.createTime),
            user: `管理员${log.adminId}`,
            action: log.operationDetail || log.operationType || '未知操作'
          }))

        if (this.latestLogs.length === 0) {
          ElMessage.info('暂无操作日志')
        }
      } catch (error) {
        console.error('获取最新日志失败:', error)
        ElMessage.error('获取最新日志失败')
        this.latestLogs = []
      }
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      try {
        const dateStr = date.toString()
        if (dateStr.includes('T')) {
          const d = new Date(dateStr)
          if (isNaN(d.getTime())) {
            return ''
          }
          return d.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          })
        }
        return dateStr
      } catch (error) {
        console.error('日期格式化错误:', error)
        return ''
      }
    },

    // 获取管理员信息
    async fetchAdminInfo() {
      try {
        console.log('开始获取管理员信息...')
        const userStore = useUserStore()
        
        console.log('当前用户信息:', userStore.userInfo)
        
        if (!userStore.userInfo) {
          throw new Error('未找到用户信息')
        }

        // 直接使用userStore中的用户信息
        this.adminInfo = {
          username: userStore.userInfo.username,
          role: userStore.userInfo.role,
          realName: userStore.userInfo.realName || '未知姓名',
          email: userStore.userInfo.email || '未设置邮箱',
          phone: userStore.userInfo.phone || '未设置电话',
          lastLoginTime: this.formatDate(userStore.userInfo.lastLogin) || '未知'
        }
        
        console.log('处理后的管理员信息:', this.adminInfo)
      } catch (error) {
        console.error('获取管理员信息失败:', error)
        ElMessage.error('获取管理员信息失败')
        this.adminInfo = {
          username: '未知管理员',
          role: '未知角色',
          realName: '未知姓名',
          email: '未设置邮箱',
          phone: '未设置电话',
          lastLoginTime: '未知'
        }
      }
    },

    // 导航方法
    goToFeedbackResponses() {
       this.$router.push({ name: 'admin-feedback-responses' });
    },
    goToUserInfo() {
       this.$router.push({ name: 'admin-user-info' });
    },
    goToQuestionManagement() {
       this.$router.push({ name: 'admin-questions' });
    },
    goToLogs() {
       this.$router.push({ name: 'admin-logs' });
    },
    goToAdminInfo() {
      this.$router.push({ name: 'admin-info' });
    }
  },

  mounted() {
    console.log('AdminIndex组件挂载，开始初始化数据...')
    // 页面加载时获取数据
    this.fetchFeedbackStats()
    this.fetchUserStats()
    this.fetchQuestionStats()
    this.fetchLatestLogs()
    this.fetchAdminInfo()

    const userStore = useUserStore()
    console.log('当前用户状态:', {
      isLoggedIn: userStore.getIsLoggedIn,
      isAdmin: userStore.isAdmin,
      userInfo: userStore.userInfo
    })

    // 添加登出检查
    if (!userStore.getIsLoggedIn) {
      console.log('用户未登录，重定向到登录页面')
      this.$router.push('/login')
      return
    }
    
    // 检查是否是管理员
    if (!userStore.isAdmin) {
      console.log('用户不是管理员，重定向到首页')
      this.$router.push('/home')
      return
    }
  }
};
</script>

<style scoped>
.admin-dashboard-container {
  padding: 20px;
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.dashboard-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #555;
}

.card-content {
  padding: 10px;
  min-height: 120px;
}

.log-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 150px;
  overflow-y: auto;
}

.log-list li {
  background-color: #f5f7fa;
  padding: 8px;
  margin-bottom: 5px;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.chart-container {
   position: relative;
   height: 200px;
}

.aligned-cards-row .card-content {
  min-height: 120px;
}

.el-card:hover{
  box-shadow: 0 4px 19px rgba(0, 0, 0, 0.25);
}

.info-text {
  color: #333;
  font-size: 13px;
}

:deep(.el-descriptions__label) {
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  background-color: #fff;
}

:deep(.el-descriptions__body) {
  background-color: #fff;
}

:deep(.el-descriptions__table) {
  margin: 0;
}

:deep(.el-descriptions__cell) {
  padding: 8px !important;
}

/* 可以根据需要调整更多样式 */
</style> 